//
//  ReportDetailViewController.m
//  suRead
//
//  Created by 李 诗洋 on 15/11/13.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "ReportDetailViewController.h"
#import "Masonry.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "ShareService.h"
#import "ServiceNews.h"
#import "M_Report.h"
#import "NewsCommentViewController.h"
#import "FMDBHelpers.h"
#import <MobLink/MobLink.h>
#import <MobLink/MLSDKScene.h>

@interface ReportDetailViewController ()

@property (nonatomic,strong) UIWebView *newsWebView;
@property (strong, nonatomic)  M_Report *report;

@property (nonatomic,assign) CGFloat fontSizeScaleRate;

@property (nonatomic,assign) NSString *mobid;
@end

@implementation ReportDetailViewController

- (void)getMobId
{
    // 构造自定义参数（可选）
    NSMutableDictionary *customParams = [NSMutableDictionary dictionary];
    customParams[@"type"] = @"baoLiaoDetail";
    customParams[@"baoLiaoId"] = self.baoLiaoId;
    // 根据路径、来源以及自定义参数构造scene
    MLSDKScene *scene = [[MLSDKScene alloc] initWithMLSDKPath:@"" source:@"iOS" params:customParams];
    // 请求MobId
    __weak typeof(self) weakSelf = self;
    
    [MobLink getMobId:scene result:^(NSString *mobid, NSError *error) {
        weakSelf.mobid = mobid;
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fontSizeScaleRate = 1.0f;
    self.navigationController.navigationBarHidden = YES;
    [self setNeedsStatusBarAppearanceUpdate];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weak_self = self;
    
    self.newsWebView = [UIWebView new];
    self.newsWebView.backgroundColor=[UIColor clearColor];
    for (UIView *subView in [self.newsWebView subviews])
    {
        if ([subView isKindOfClass:[UIScrollView class]])
        {
            //((UIScrollView *)subView).bounces = NO; //去掉UIWebView的底图
            [(UIScrollView *)subView setShowsVerticalScrollIndicator:NO]; //右侧的滚动条
            [(UIScrollView *)subView setShowsHorizontalScrollIndicator:NO]; //右侧的滚动条
            
            for (UIView *scrollview in subView.subviews)
            {
                if ([scrollview isKindOfClass:[UIImageView class]])
                {
                    scrollview.hidden = YES;  //上下滚动出边界时的黑色的图片
                }
            }
        }
    }
    self.newsWebView.backgroundColor = [UIColor whiteColor];
    UIPinchGestureRecognizer *gesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(switchFontSize:)];
    [self.newsWebView addGestureRecognizer:gesture];
    
    UIView *bottomBarView = [UIView new];
    bottomBarView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.newsWebView];
    [self.view addSubview:bottomBarView];
    [bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weak_self.view);
        if (iPhoneX) {
            make.top.equalTo(bottomBarView.superview).offset(44.0f);
        } else {
            make.top.equalTo(bottomBarView.superview).offset(20.0f);
        }
        make.height.equalTo(@44.0f);
    }];
    [self.newsWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomBarView.mas_bottom);
        make.left.right.equalTo(weak_self.view);
        if (iPhoneX) {
            make.bottom.equalTo(self.newsWebView.superview).offset(-34.0f);
        } else {
            make.bottom.equalTo(self.newsWebView.superview);
        }
    }];
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //返回
        [weak_self.navigationController popViewControllerAnimated:YES];
        [weak_self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonShare setImage:[UIImage imageNamed:@"icon_zb_share"] forState:UIControlStateNormal];
    [buttonShare addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        NSString *shareUrl_ = weak_self.report.f_url;
        if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
        {
            shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
            if (self.mobid) {
                shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&mobid=%@",self.mobid]];
            }
        } else {
            if (self.mobid) {
                shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"?mobid=%@",self.mobid]];
            }
        }

        [ShareService share:weak_self url:shareUrl_ title:weak_self.report.f_title image:weak_self.report.f_thumb completion:nil];
    }];
    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    
    [bottomBarView addSubview:linelab];
    
    
    [bottomBarView addSubview:buttonBack];
    [bottomBarView addSubview:buttonShare];
    
    [linelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bottomBarView);
        make.height.equalTo(@0.5f);
    }];
    
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomBarView);
        make.left.equalTo(bottomBarView).with.offset(10.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomBarView);
        make.right.equalTo(bottomBarView).with.offset(-8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    UILabel *labelTitle = [UILabel new];
    labelTitle.textColor = [UIColor blackColor];
    labelTitle.text = @"报料详情";
    labelTitle.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:18.0f];
    [bottomBarView addSubview:labelTitle];
    [labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(labelTitle.superview);
        make.bottom.equalTo(labelTitle.superview);
        make.height.equalTo(@44.0f);
    }];
    
    [self refreshData];
}

- (void)refreshData
{
    __weak typeof(self) weak_self = self;
    [self showHUDProgress:@""];
    [ServiceNews doReportDetail:self.baoLiaoId
                        success:^(id responseObject, NSString *message)
     {
         [weak_self removeHUDProgress];
         [weak_self computeHTMLWithNews:responseObject];
         weak_self.report = responseObject;
     }
                        failure:^(NSString *message)
     {
         [weak_self removeHUDProgress];
         [weak_self showHUDText:message];
     }];
}

- (void)computeHTMLWithNews:(M_Report *)report_
{
    NSString *htmlString = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"newdetail" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
    
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"$$title$$" withString:report_.f_title];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"$$time$$" withString:report_.f_inputtime];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"$$content$$" withString:report_.f_content];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"$$reply$$" withString:report_.f_reply];
    
    [self.newsWebView loadHTMLString:htmlString baseURL:nil];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationFade;
}

- (void)switchFontSize:(UIPinchGestureRecognizer *)gesture
{
    if (gesture.state==UIGestureRecognizerStateEnded | gesture.state==UIGestureRecognizerStateCancelled) {
        
        NSString *js = @"";
        
        if (gesture.scale<1.0) {
            self.fontSizeScaleRate<=0.8?self.fontSizeScaleRate:(self.fontSizeScaleRate -= 0.1);
            
            js = [NSString stringWithFormat:@"document.body.style.fontSize = \"%.0f",self.fontSizeScaleRate*100];
            
        }
        else {
            self.fontSizeScaleRate>=1.2?self.fontSizeScaleRate:(self.fontSizeScaleRate += 0.1);
            
            js = [NSString stringWithFormat:@"document.body.style.fontSize = \"%.0f",self.fontSizeScaleRate*100];
            
        }
        js = [js stringByAppendingString:@"%\";"];
        [self.newsWebView stringByEvaluatingJavaScriptFromString:js];
    }
    
}

@end
